<?php

namespace app\service;

use Exception;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use TencentCloud\Antiddos\V20200309\Models\DDoSAIRelation;
use TencentCloud\Tcaplusdb\V20190823\Models\IdlFileInfo;
use think\facade\Filesystem;
use think\File;

/**
 * 上传管理
 *
 * user ：Du
 * Date : 2022/3/31
 * Time : 14:29
 * Class UploadServices
 * @package projects\services
 */
class UploadServices
{

    /**
     * 支持图片格式
     * User : Du
     * Date : 2022/11/22
     * Time : 12:41
     * @var array|string[]
     */
    public static array $imageType = ['image/jpg', 'image/png', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/bmp', 'image/x-png'];

    /**
     * 支持音乐格式
     * @var array|string[]
     */
    public static array $musicType = ['audio/flac', 'audio/mpeg', 'audio/x-wav', '', '', '', ''];


    /**
     * 获取上传token
     *
     * User : Du
     * Date : 2022/3/31
     * Time : 16:58
     * @return string
     */
    public static function getToken(): string
    {
        $cfg = [
            'access' => env('qiniu.accesskey'),
            'secret' => env('qiniu.secrekey'),
            'bucket' => env('qiniu.bucket'),
        ];
        $auth = new Auth($cfg['access'], $cfg['secret']);
        // 创建一个过期时间为1小时的临时上传令牌
        return $auth->uploadToken($cfg['bucket']);
    }

    /**
     * 上传图片
     * User : Du
     * Date : 2022/11/22
     * Time : 16:32
     * @param array $request
     * @return array|string
     * @throws Exception
     */
    public static function image(array $request)
    {
        $file = request()->file('file');
        $dirName = $request['type'] ?? 'other';
        $status = $request['status'] ?? 0;
        if ($status === 0 && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
            $status = 1;
        }
        if ($file) {  //文件域上传
            if ($file->getSize() <= 0) {
                return '请重新选择图片';
            }
            if (!in_array($file->getMime(), self::$imageType, true)) {
                return '图片格式错误';
            }
        } else {
            return '暂未支持该格式上传';
        }
        $size = getSize($file->getSize());
        $fileName = $file->getOriginalName();
        $savePath = 'tp/' . $dirName;
        if ((int)$status === 1) {
            //上传到存储后保存的文件名
            $path = $file->getPathname();
            $hashName = explode('.', $file->hashName())[1];
            return self::uploadQiNiu($savePath, $fileName, $hashName, $path, $size);
        }
        return self::uploadLocal($savePath, $file, $fileName, $size);
    }

    /**
     * 保持七牛云
     * @param string $savePath
     * @param string $fileName
     * @param string $hashName
     * @param string $path
     * @param string $size
     * @return array|string
     * @throws Exception
     */
    private static function uploadQiNiu(string $savePath, string $fileName, string $hashName, string $path, string $size)
    {
        // 初始化 UploadManager 对象并进行文件的上传。
        $accessKey = env('qiniu.accesskey');
        $secretkey = env('qiniu.secretkey');
        $bucket = env('qiniu.bucket');
        $auth = new Auth($accessKey, $secretkey);
        $token = $auth->uploadToken($bucket);
        $savePath = $savePath . '/' . date('Ymd');
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        [$res, $err] = (new UploadManager())->putFile($token, $savePath . '/' . $hashName, $path, null, 'application/octet-stream', true, null, 'v2');
        if ($err !== null) {
            return '上传失败，配置错误';
        }
        $res = imagePath($res['key']);
        $res['title'] = $fileName;
        $res['size'] = $size;
        return $res;
    }

    /**
     * 保存本地
     * @param string $savePath
     * @param File $file
     * @param string $fileName
     * @param string $size
     * @return string[]
     */
    private static function uploadLocal(string $savePath, File $file, string $fileName, string $size): array
    {
        if (!is_dir($savePath)) {
            mkdir($savePath);
        }
        $res = Filesystem::disk('public')->putFile($savePath, $file);
        $res = imagePath($res);
        $res['title'] = $fileName;
        $res['size'] = $size;
        return $res;
    }

    /**
     * 上传视频
     *
     * User : Du
     * Date : 2022/4/1
     * Time : 17:03
     * @param array $request
     * @return bool|string[]
     * @throws Exception
     */
    public static function video(array $request)
    {
        set_time_limit(120);
        ini_set('memory_limit', '2000M');
        $total = (int)$request['total'] ?? 0;
        $number = (int)$request['number'] ?? 0;
        $time = (int)$request['time'] ?? date('H:i:s');
        $file = $_FILES['file'];
        $filename = explode('.', $file['name']);
        $key = md5($file['name'] . $time);
        $filePath = public_path() . 'uploads/' . $key . '.' . $filename['1'];//确定上传的文件名
        if (!file_exists($filePath)) {
            fopen($filePath, "w");
            move_uploaded_file($file['tmp_name'], $filePath);
        }
//        file_put_contents($filePath, file_get_contents($file['tmp_name']), FILE_APPEND);
        if ($number + 1 === $total) {
//            $name = md5($file['name'] . date('Ymd')) . '.' . $filename[1];
//            $path = 'video/' . date('Ymd') . '/' . $name;
//            $ak = env('qiniu.ak');;
//            $sk = env('qiniu.sk');;
//            $domain = env('qiniu.domain');
//            $bucket = env('qiniu.bucket');
//            $auth = new Auth($ak, $sk);
//            $token = $auth->uploadToken($bucket);
//            $upload = new UploadManager();
//            list($ret, $err) = $upload->putFile($token, $path, $filePath, null, 'application/octet-stream', false, null, 'v2');
//            if ($err !== null) {
//                return false;
//            } else {
//                return ['url' => $domain . '/' . $path, 'path' => $path];
//            }
            return ['path' => $filePath, 'url' => $filePath];
        }
        return ['status' => 'ok'];
    }

    /**
     * 音乐上传
     * @return array|string|string[]
     * @throws Exception
     */
    public static function music()
    {
        $file = request()->file('file');
        $dirName = $request['type'] ?? 'music';
        if ($file || $file->getSize() <= 0) {  //文件域上传
            if (!in_array($file->getMime(), self::$musicType, true)) {
                return '音乐格式错误';
            }
        } else {
            return '请选择上传文件';
        }
        $size = getSize($file->getSize());
        // 上传到存储后保存的文件名
        $savePath = 'tp/' . $dirName;
        $fileName = $file->getOriginalName();
        //收听流量收费 放弃上传七牛云------
//        return self::uploadQiNiu($savePath, $fileName, $hashName, $path, $size);
        return self::uploadLocal($savePath, $file, $fileName, $size);
    }


    /**
     * 删除文件
     * User : Du
     * Date : 2022/12/2
     * Time : 15:52
     * @param array $request
     * @return bool
     */
    public static function delete(array $request): bool
    {
        if (!isset($request['path']) || !$request['path']) {
            return false;
        }
        $accessKey = env('qiniu.accesskey');
        $secretkey = env('qiniu.secretkey');
        $bucket = env('qiniu.bucket');
        $auth = new Auth($accessKey, $secretkey);
        $config = new Config();
        list($res, $err) = (new BucketManager($auth, $config))->delete($bucket, $request['path']);
        if ($err) {
            return false;
        }
        return true;
    }
}